<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class FunctionModel extends Model
{
    use HasFactory;

    protected $table = 'functions';

    protected $fillable = [
        'code',
        'name',
        'level',
        'menu_id',
        'description',
        'dependencies',
        'status',
        'sort_order',
    ];

    protected $casts = [
        'dependencies' => 'array',
    ];

    /**
     * 获取所属菜单
     */
    public function menu(): BelongsTo
    {
        return $this->belongsTo(Menu::class);
    }

    /**
     * 获取关联的权限节点
     */
    public function permissionNodes(): BelongsToMany
    {
        return $this->belongsToMany(PermissionNode::class, 'function_permissions')
            ->withTimestamps();
    }

    /**
     * 获取分配了此功能的角色
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'role_function_permissions')
            ->withPivot(['auto_granted', 'granted_by', 'granted_at'])
            ->withTimestamps();
    }

    /**
     * 检查功能是否启用
     */
    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    /**
     * 检查是否为核心功能
     */
    public function isCore(): bool
    {
        return $this->level === 'core';
    }

    /**
     * 检查是否为可选功能
     */
    public function isOptional(): bool
    {
        return $this->level === 'optional';
    }

    /**
     * 获取功能级别标签
     */
    public function getLevelLabelAttribute(): string
    {
        return match ($this->level) {
            'core' => '必备功能',
            'optional' => '可选功能',
            default => $this->level,
        };
    }

    /**
     * 获取状态标签
     */
    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            'active' => '启用',
            'inactive' => '禁用',
            default => $this->status,
        };
    }

    /**
     * 获取依赖功能列表
     */
    public function getDependencyFunctions()
    {
        if (empty($this->dependencies)) {
            return collect();
        }

        return static::whereIn('id', $this->dependencies)->get();
    }

    /**
     * 检查是否可以被用户使用
     */
    public function canBeUsedBy(User $user): bool
    {
        // 检查用户是否有此功能权限
        if (!$user->hasFunctionPermission($this->code)) {
            return false;
        }

        // 检查依赖功能权限
        if (!empty($this->dependencies)) {
            foreach ($this->dependencies as $dependencyId) {
                $dependency = static::find($dependencyId);
                if ($dependency && !$user->hasFunctionPermission($dependency->code)) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 作用域：活跃功能
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * 作用域：按菜单筛选
     */
    public function scopeByMenu($query, $menuId)
    {
        return $query->where('menu_id', $menuId);
    }

    /**
     * 作用域：核心功能
     */
    public function scopeCore($query)
    {
        return $query->where('level', 'core');
    }

    /**
     * 作用域：可选功能
     */
    public function scopeOptional($query)
    {
        return $query->where('level', 'optional');
    }
}
